package com.yisoo.homework.whiteboard.command;

import com.yisoo.homework.whiteboard.ui.canvas.MyCanvas;
import com.yisoo.homework.whiteboard.ui.component.shape.AbstractShape;
import com.yisoo.homework.whiteboard.ui.component.shape.PenShape;
import com.yisoo.homework.whiteboard.utils.CanvasUtils;

import java.util.List;

/**
 * TODO
 *
 * @author mmciel 761998179@qq.com
 * @version 1.0.0
 * @date 2022/12/22 14:57
 * @update none
 */
public class ShapeCommand implements Command {
    private final MyCanvas canvas = MyCanvas.getInstance();

    @Override
    public void execute(AbstractShape shape, Boolean isShow) {
        canvas.getShapes().add(shape);
        if (isShow) {
            shape.show(CanvasUtils.getGraphicsAfterReset());
        }
    }

    @Override
    public void undo(Boolean isShow) {
        // 如果是三个画笔+橡皮需要撤销，需要一下全撤掉，使用PenShape做分割
        List<AbstractShape> shapes = canvas.getShapes();
        int limit = shapes.size() - 1;
        if (limit >= 0) {
            // 是PenShape结尾的
            if (shapes.get(limit) instanceof PenShape) {
                // 删掉分隔符
                shapes.remove(limit);
                limit--;
                // 是笔迹
                if (limit >= 0
                        && shapes.get(limit) instanceof PenShape
                        && !shapes.get(limit).getClass().equals(PenShape.class)) {
                    for (int i = limit; i >= 0; i--) {
                        // 只要是笔迹就删除
                        if (shapes.get(i) instanceof PenShape && !shapes.get(i).getClass().equals(PenShape.class)) {
                            shapes.remove(i);
                        }
                        // 没有了就是删完了
                        else {
                            break;
                        }
                    }
                }

            } else {
                shapes.remove(limit);
            }
        }
        if (isShow) {
            CanvasUtils.reset().addImage().redraw().show();
        }
    }

    @Override
    public void redo(Boolean isShow) {
        canvas.getShapes().clear();
        if (isShow) {
            CanvasUtils.reset().removeImage().redraw().show();
        }
    }
}
